<template>
  <router-view></router-view>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter, RouteRecordRaw } from 'vue-router'

import Menu from '@/types/menu'
import { findMenus } from '@/api/menuApi'

import useSidebarStore from '@/store/modules/sidebar'

const sidebar = useSidebarStore()

const router = useRouter()
const Layout = () => import('@/views/layout/index.vue')
  
onMounted(async () => {
  const menuResponse = await findMenus()
  if (menuResponse.status !== 200) {
    return
  }
  sidebar.setMenuList(menuResponse.data)
  menuResponse.data.forEach((menu: Menu) => {
    const routeInfo: RouteRecordRaw = {
      path: menu.path,
      component: menu.layout === 'default' ? Layout : () => import(`../../../../src/views/${menu.componentPath}`),
      name: menu.name,
      meta: menu.meta,
      redirect: '',
      children: []
    }
    if (!menu.children) {
      delete routeInfo.redirect
    }
    if (menu.children) {
      routeInfo.redirect = menu.redirect
      routeInfo.children = menu.children.map((m) => {
        return {
          path: m.path,
          name: m.name,
          component: () => import(`../../../../src/views/${m.componentPath}`),
          meta: m.meta
        } as RouteRecordRaw
      })
    }
    router.addRoute(routeInfo)
  })
})
</script>

<style scoped></style>

